const app = getApp();
import CanvasDrag from '../../components/canvas-drag/canvas-drag';
Page({

  /**
   * 页面的初始数据
   */
  
  data: {
    hiddenCollect:true,//隐藏
    hiddenMe:false,
    userInfo: {}, //用户信息
    tempImage: {},
    techoImage: '', //完成了的手账图片地址
    graph: {},
    chooseEmpty: false,
    template: {}, //模板信息
    imglist: [],
    isClear: false,
    penColor: 'black',
    textColor: 'black',
    inputText: "", //输入框里的内容
    bgColor: 'black',
    lineWidth: 5,
    curContexts: [],
    pathCount: 0,
    contextCount: 0,
    tool_list: [{
        id: 1,
        src: '/icon/pen.png',
        isClick: true,
      },
      {
        id: 2,
        src: '/icon/shape.png',
        isClick: false,
      },
      {
        id: 3,
        src: '/icon/photo.png',
        isClick: false,
      },
      {
        id: 4,
        src: '/icon/text.png',
        isClick: false,
      },
      {
        id: 5,
        src: '/icon/sticker.png',
        isClick: false,
      },
      {
        id: 6,
        src: '/icon/scissors.png',
        isClick: false,
      },
    ],
    tool_list1: [
      // {
      //   id: 7,
      //   src: '/icon/pre.png',
      //   f: "onUndo"
      // },
      {
        id: 8,
        src: '/icon/save.png',
        f: 'save_click'
      },
      {
        id: 9,
        src: '/icon/next.png',
        f: "onClearCanvas"
      },
      
    ],
    //触摸颜色
    pencolor_list: [{
        id: 1,
        color: "black",
        isClick: true,
      },
      {
        id: 2,
        color: "#ffff00",
        isClick: false,
      },
      {
        id: 3,
        color: "#ff9900",
        isClick: false,
      },
      {
        id: 4,
        color: "#ff3333",
        isClick: false,
      },
      {
        id: 5,
        color: "#ff3399",
        isClick: false,
      },
      {
        id: 6,
        color: "#ccff99",
        isClick: false,
      },
      {
        id: 7,
        color: "#ccff00",
        isClick: false,
      },
      {
        id: 8,
        color: "#3399ff",
        isClick: false,
      },
      {
        id: 9,
        color: "#99cc33",
        isClick: false,
      },
    ], 
    //触摸粗细
    tickness_list: [{
      id: 1,
      tickness: 4,
      isClick: true,
    },
    {
      id: 2,
      tickness: 6,
      isClick: false,
    },
    {
      id: 3,
      tickness: 8,
      isClick: false,
    },
    {
      id: 4,
      tickness: 10,
      isClick: false,
    },
    {
      id: 5,
      tickness: 12,
      isClick: false,
    },
    {
      id: 6,
      tickness: 14,
      isClick: false,
    },
    ],
    //背景颜色
    bg_list: [{
        id: 1,
        color: "black",
        isClick: true,
      },
      {
        id: 2,
        color: "#ffff00",
        isClick: false,
      },
      {
        id: 3,
        color: "#ff9900",
        isClick: false,
      },
      {
        id: 4,
        color: "#ff3333",
        isClick: false,
      },
      {
        id: 5,
        color: "#ff3399",
        isClick: false,
      },
      {
        id: 6,
        color: "#ccff99",
        isClick: false,
      },
      {
        id: 7,
        color: "#ccff00",
        isClick: false,
      },
      {
        id: 8,
        color: "#3399ff",
        isClick: false,
      },
      {
        id: 9,
        color: "#99cc33",
        isClick: false,
      },
    ],
    //文字颜色
    textcolor_list: [{
        id: 1,
        color: "black",
        isClick: true,
      },
      {
        id: 2,
        color: "#ffff00",
        isClick: false,
      },
      {
        id: 3,
        color: "#ff9900",
        isClick: false,
      },
      {
        id: 4,
        color: "#ff3333",
        isClick: false,
      },
      {
        id: 5,
        color: "#ff3399",
        isClick: false,
      },
      {
        id: 6,
        color: "#ccff99",
        isClick: false,
      },
      {
        id: 7,
        color: "#ccff00",
        isClick: false,
      },
      {
        id: 8,
        color: "#3399ff",
        isClick: false,
      },
      {
        id: 9,
        color: "#99cc33",
        isClick: false,
      },
    ],
    sticker_list: [],
    collect_list: [],
  },
  shghnn:function(){
    this.setData({
      hiddenCollect:true,
        hiddenMe:false,
    })
  },
  //点击我的隐藏收藏 出现我的

shghnn1:function(){
  this.setData({
    hiddenCollect:false,
      hiddenMe:true,
  })
},
  /**
   * 点击工具箱的工具
   */
  tool_click: function (e) {
    //改变点击状态
    let index = e.target.dataset.index;
    let temp_str = 'tool_list[' + index + '].isClick';
    let list = this.data.tool_list;
    console.log(temp_str);
    if (!this.data.tool_list[index].isClick) {
      for (var i = 0; i < list.length; i++) {
        let temp_str2 = 'tool_list[' + i + '].isClick';
        if (list[i].isClick) {
          this.setData({
            [temp_str2]: false
          })
        }
      }
      this.setData({
        [temp_str]: true
      })
    } else {
      if (index < 6) {
        this.setData({
          [temp_str]: false
        })
      }
    }
    //点击添加图片
    if (this.data.tool_list[2].isClick) {
      this.onAddImage()
    }
    //点击输入文字
    if (this.data.tool_list[3].isClick) {
    }
    //点击增添贴纸
    if (this.data.tool_list[4].isClick) {
      wx.request({
        url: `${app.globalData.url}/editor/sticker`,
        header: {
          'Content-Type': 'application/x-www-from-urlencoded',
          'authorization': `${wx.getStorageSync('login_key')}`
        },
        success: res => {
          console.log(res)
          if (res.statusCode == 200) {
            this.setData({
              sticker_list: res.data.pay_sticker,
              collect_list:res.data.show
            })
          }
        },
        faile: err => {
          console.error(err)
        }
      })
    }
  },
  //加下划线
  onAddXhx1() {
    this.setData({
      graph: {
        w: 120,
        h: 120,
        type: 'shape',
        url: '../../assets/images/xhx1.png',
      }
    });
  },
  onAddXhx2() {
    this.setData({
      graph: {
        w: 120,
        h: 120,
        type: 'shape',
        url: '../../assets/images/xhx2.png',
      }
    });
  },

  onAddXhx3() {
    this.setData({
      graph: {
        w: 120,
        h: 120,
        type: 'shape',
        url: '../../assets/images/xhx3.png',
      }
    });
  },
  onAddXhx4() {
    this.setData({
      graph: {
        w: 120,
        h: 120,
        type: 'shape',
        url: '../../assets/images/xhx4.png',
      }
    });
  },
  /**加图形 */
  onAddReact() {
    this.setData({
      graph: {
        w: 120,
        h: 120,
        type: 'shape',
        url: '../../assets/images/react.jpg',
      }
    });
  },
  onAddTrangle() {
    this.setData({
      graph: {
        w: 120,
        h: 120,
        type: 'shape',
        url: '../../assets/images/trangle.jpg',
      }
    });
  },
  onAddParallelogram() {
    this.setData({
      graph: {
        w: 120,
        h: 120,
        type: 'shape',
        url: '../../assets/images/parallelogram.jpg',
      }
    });
  },
  onAddCircle() {
    this.setData({
      graph: {
        w: 120,
        h: 120,
        type: 'shape',
        url: '../../assets/images/circle.jpg',
      }
    });
  },
  onAddLine() {
    this.setData({
      graph: {
        w: 120,
        h: 120,
        type: 'shape',
        url: '../../assets/images/line.jpg',
      }
    });
  },
  /**
   * 添加图片
   */
  onAddImage() {
    wx.chooseImage({
      success: (res) => {
        wx.getImageInfo ({
          src:res.tempFilePaths[0],
          success:res=>{
            console.log(res)
            const key = res.width/res.height
            this.setData({
              graph: {
                w: res.width/5,
                h: res.height/5,
                type: 'image',
                url: res.path,
              }
            });
          }
        })
      }
    })
  },

  /**
   * 添加文本
   */
   setValue: function (e) {
    this.setData({
      graph: {
        type: 'text',
        text:e.detail.value
    }
    })
  },
  getValue: function (e) { //获得输入框内容
    CanvasDrag.changeFontText(e.detail.value) //改变选中框内容
  },
  /**
   * 改变背景颜色
   */
  onChangeBgColor() {
    CanvasDrag.changeBgColor('white');
  },

  onImport() {
    // 有背景
    // let temp_theme = [{"type":"bgColor","color":"yellow"},{"type":"image","url":"../../assets/images/test.jpg","y":98.78423143832424,"x":143.78423143832424,"w":104.43153712335152,"h":104.43153712335152,"rotate":-12.58027482265038,"sourceId":null},{"type":"text","text":"helloworld","color":"blue","fontSize":24.875030530031438,"y":242.56248473498428,"x":119.57012176513672,"w":116.73966979980469,"h":34.87503053003144,"rotate":8.873370699754087}];
    // 无背景
    let temp_theme = [{
      "type": "image",
      "url": "../../assets/images/test.jpg",
      "y": 103,
      "x": 91,
      "w": 120,
      "h": 120,
      "rotate": 0,
      "sourceId": null
    }, {
      "type": "text",
      "text": "helloworld",
      "color": "blue",
      "fontSize": 20,
      "y": 243,
      "x": 97,
      "rotate": 0
    }];
    if (this.data.temp.text) {
      CanvasDrag.initByArr(this.data.temp.text)
    } else {
      CanvasDrag.initByArr(temp_theme);
    }
  },
  /**
   * 清空画布
   */
  onClearCanvas: function (event) {
    let _this = this;
    var canvasBg = null
    CanvasDrag.clearCanvas();
  },

  onUndo: function (event) {
    CanvasDrag.undo();
  },
  /**
   * 回退一步
   */
  recall: function () {
    this.context.clearRect(0, 0, 750, 1280);
    this.context.draw();
    if (this.data.pathCount > 0) {
      for (var i = 0; i < this.data.pathCount - 1; i++) {
        for (var j = 0; j < this.data.curContexts[i].length; j++) {
          wx.drawCanvas({
            canvasId: 'myCanvas',
            reserve: true,
            actions: this.data.curContexts[i][j] // 获取绘图动作数组
          });
        }
      }
      var pathCount = this.data.pathCount - 1;
      this.data.curContexts[pathCount] = null;
      this.setData({
        pathCount: pathCount,
        contextCount: 0,
      });
    }
  },
  //导出模板
  temp : [], //用户创建手账信息
  out:function(){
    return new Promise((resolve)=>{
      resolve(CanvasDrag.exportJson().then((imgArr) => {
        //console.log(JSON.stringify(imgArr));
        this.temp = imgArr
      }).catch((e) => {
          this.temp = {
            type: 'JSON',
            text: e,
          }
      })
      )
    })
  },
  //上传手账相关信息
  push:function(){
    wx.request({
      url: `${app.globalData.url}/user/saveTecho`,
      header: {
        'Content-Type': 'application/json',
        'authorization': `${wx.getStorageSync('login_key')}`
      },
      method: 'POST',
      data:{
        temp:this.temp,
      },
      success: res => {
        console.log(res)
        if (res.statusCode === 200) {
          //手账中有图片的话上传图片文件到服务器
          this.temp.map((item, index) => {
            if (item.type == "image") {
              wx.uploadFile({
                filePath: item.url,
                name: 'image',
                header: {
                  'Content-Type': 'application/x-www-from-urlencoded',
                  'authorization': `${wx.getStorageSync('login_key')}`
                },
                url: `${app.globalData.url}/image/?num=${index}&x=${item.x}&y=${item.y}&w=${item.w}&h=${item.h}&r=${item.rotate}`,
              })
            }
          })
          //上传手账图片到服务器
          //导出图片
          CanvasDrag.export()
            .then((filePath) => {
              console.log(filePath);
              // wx.previewImage({
              //   urls: [filePath],
              // })//预览大图
              wx.uploadFile({
                filePath: filePath,
                name: 'techoCover',
                url: `${app.globalData.url}/user/saveCover`,
                header: {
                  'Content-Type': 'application/x-www-from-urlencoded',
                  'authorization': `${wx.getStorageSync('login_key')}`
                },
              })
            })
            .catch((e) => {
              console.error(e);
            })
          if (res.data == "保存成功了") {
            wx.showModal({
              title: '提示',
              content: '保存成功啦',
              image: this.data.techoImage,
              confirmText: "回到手账",
              cancelText:"继续记录",
              success: function (res) {
                if (res.confirm) { //这里是点击了确定以后
                  wx.navigateTo({
                    url: '../show/show',
                  })
                } else { //这里是点击了继续记录以后
                  console.log('用户点击取消');
                }
              }
            })
          }
        } 
      }
    })
  },
  /**
   * 点击保存
   */
  save_click: function () {
    if(app.globalData.hasUserInfo){
      this.out().then(()=>this.push())      
    }else{
      wx.showModal({
        title: '提示',
        content: '你还没有登录哦',
        success: function (res) {
          if (res.confirm) { //这里是点击了确定以后
          } else { //这里是点击了取消以后
            console.log('用户点击取消');
          }
        }
      })
    }    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      userInfo: app.globalData.userInfo
    })
    const chooseEmpty = options.chooseEmpty
    console.log(chooseEmpty)
    if (chooseEmpty == "true") {
      this.setData({
        chooseEmpty: !this.data.chooseEmpty
      })
    } else { //选择模板进入
      if (options.template_id) {
        console.log(`${app.globalData.url}/editor/template/${app.globalData.userInfo.user_id}&${options.template_id}`)
        var template_sticker = {} //模板贴纸信息
        wx.request({
          url: `${app.globalData.url}/editor/template/${app.globalData.userInfo.user_id}&${options.template_id}`,
          success: res => {
            console.log(res.data);
            template_sticker = res.data.slice(1),
            this.setData({
              template: res.data[0],
            })
            //渲染背景
            let template_bg = this.data.template[0].template_bg //背景图片名
            let id = this.data.template[0].template_id //模板id
            wx.getImageInfo({
              src: `${app.globalData.url}/editor/image/${template_bg}`,
              success: res => {
                CanvasDrag.changeBgImage(res.path, template_bg, id); //渲染背景
              }
            })
            const position = template_sticker[0]
            const stickers = template_sticker.slice(1)
            console.log(position)
            console.log(stickers)
            for (let i = 0; i < stickers.length; i++) {
              console.log(1)
              //渲染贴纸
              let locationArr = position[i].sticker_location.match(/\d+/g);
              let sizeArr = position[i].sticker_size.match(/\d+/g);
              let sticker_name = stickers[i][0].sticker_name
              let id = stickers[i][0].sticker_id
              wx.getImageInfo({
                src: `${app.globalData.url}/editor/image/${sticker_name}`,
                success: res => {
                  console.log(2)
                  this.setData({
                    graph: {
                      x: parseInt(locationArr[0]),
                      y: parseInt(locationArr[1]),
                      w: parseInt(sizeArr[0]),
                      h: parseInt(sizeArr[1]),
                      id: id,
                      type: 'sticker',
                      url: res.path,
                      sticker_name: sticker_name,
                    }
                  })
                }
              })
            }
          }
        })
      } else if (options.techo_id) {//修改已有的手账
        console.log(options.techo_id)
        var techo = {}//修改的手账信息
        wx.request({
          url: 'https://www.h5fd.xyz:2021/user/showTecho',
          header:{'Content-Type':'application/x-www-from-urlencoded','authorization':`${wx.getStorageSync('login_key')}`},
          success:res=>{
            res.data.map((item)=>{
              if(item.title.techo_id==options.techo_id){
                techo = item
              }
            })
            console.log(techo)
            //渲染背景
            if(techo.title.techo_template_id.indexOf('#')>0){//背景有颜色
                CanvasDrag.changeBgColor(techo.title.techo_template_id);
            }else if(techo.title.techo_template_id.indexOf('jpg')>0){//背景有图片
              let techo_bg = techo.title.techo_template_id //背景图片名
              let id = techo.title.techo_id//手账id
              wx.getImageInfo({
                src: `${app.globalData.url}/editor/image/${techo_bg}`,
                success: res => {
                  CanvasDrag.changeBgImage(res.path, techo_bg, null, id); //渲染背景
                }
              })
            }
            //渲染贴纸、图片、形状、文字
            var max = techo.picture.length +techo.shape.length + techo.sticker.length + techo.word.length+1
            for(let num =1; num<max; num++){
              techo.picture.map(item=>{
                if(item.num ==num ){
                  wx.getImageInfo({
                    src: `${app.globalData.url}/editor/showPic/${item.picture_name}`,
                    success: res => {
                      this.setData({
                        graph: {
                          type: 'image',
                          x: item.x,
                          y: item.y,
                          w: item.w,
                          h: item.h,
                          url: res.path,
                        }
                      })
                    }
                  })
                }
              })
              techo.shape.map(item=>{
                if(item.num ==num ){
                  this.setData({
                    graph: {
                      type: 'shape',
                      x: item.x,
                      y: item.y,
                      w: item.w,
                      h: item.h,
                      url: item.shade_address,
                    }
                  })
                }
              })
              techo.sticker.map(item=>{
                if(item.num ==num ){
                  wx.getImageInfo({
                    src: `${app.globalData.url}/editor/image/${item.sticker_name}`,
                    success: res => {
                      this.setData({
                        graph: {
                          type: 'sticker',
                          x: item.x,
                          y: item.y,
                          w: item.w,
                          h: item.h,
                          url: res.path,
                          sticker_name: item.sticker_name,
                          id:item.sticker_id,
                        }
                      })
                    }
                  })
                }
              })
              techo.word.map(item=>{
                if(item.num==num){
                  this.setData({
                    graph: {
                      type: 'text',
                      x: item.x,
                      y: item.y,
                      w: item.w,
                      h: item.h,
                      url: item.shade_address,
                      fontsize:item.fontsize,
                      color:item.word_color,
                      text:item.word_content
                    }
                  })
                }
              })
            }
          }
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //重新获取用户已经拥有的贴纸
    wx.request({
      url: `${app.globalData.url}/editor/sticker`,
      header: {
        'Content-Type': 'application/x-www-from-urlencoded',
        'authorization': `${wx.getStorageSync('login_key')}`
      },
      success: res => {
        if (res.statusCode == 200) {
          this.setData({
            sticker_list: res.data.pay_sticker,
            collect_list:res.data.show
          })
        }
      },
      faile: err => {
        console.error(err)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 画笔选择
   */
  ticknessSelect: function (options) {
    let index = options.target.dataset.index;
    let temp_str = 'tickness_list[' + index + '].isClick';
    let list = this.data.tickness_list;
    console.log(temp_str);
    for (var i = 0; i < list.length; i++) {
      let temp_str2 = 'tickness_list[' + i + '].isClick';
      if (list[i].isClick) {
        this.setData({
          [temp_str2]: false
        })
      }
    }
    this.setData({
      [temp_str]: true
    })
    console.log(list);
    var lineWidth = options.target.dataset.param;
    console.log("lineWidth:" + lineWidth);
    this.setData({
      lineWidth: lineWidth,
    });
  },

  /**
   * 颜色选择
   */
  colorSelect: function (options) {
    //如果是背景改变颜色
    if (this.data.tool_list[5].isClick) {
      let index = options.target.dataset.index;
      let temp_str = 'bgcolor_list[' + index + '].isClick';
      let list = this.data.bg_list;
      console.log(temp_str);
      for (var i = 0; i < list.length; i++) {
        let temp_str2 = 'bg_list[' + i + '].isClick';
        if (list[i].isClick) {
          this.setData({
            [temp_str2]: false
          })
        }
      }
      this.setData({
        [temp_str]: true
      })
      console.log(list);
      var bgColor = options.target.dataset.param;
      console.log("bgColor:" + bgColor);
      this.setData({
        isClear: false,
        bgColor: bgColor,
      });
      CanvasDrag.changeBgColor(this.data.bgColor);
    }
    //如果是文字改变颜色
    if (this.data.tool_list[3].isClick) {
      let index = options.target.dataset.index;
      let temp_str = 'textcolor_list[' + index + '].isClick';
      let list = this.data.textcolor_list;
      console.log(temp_str);
      for (var i = 0; i < list.length; i++) {
        let temp_str2 = 'textcolor_list[' + i + '].isClick';
        if (list[i].isClick) {
          this.setData({
            [temp_str2]: false
          })
        }
      }
      this.setData({
        [temp_str]: true
      })
      console.log(list);
      var textColor = options.target.dataset.param;
      console.log("textColor:" + textColor);
      this.setData({
        isClear: false,
        textColor: textColor,
      });
      CanvasDrag.changFontColor(this.data.textColor);
    }
  },

  /**
   * 清除涂鸦信息
   */
  clearCanvas: function (options) {
    console.log("clearCanvas");
    this.setData({
      isClear: !this.data.isClear
    });
  },
  img_w_show() {
    var _this = this;
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        _this.setData({
          imglist: _this.data.imglist.concat(tempFilePaths)
        })
      }
    })
  },
  /**
   * 点击贴纸
   */
  collect_click:function (e) {
    const index = e.target.dataset.index;
    const list = this.data.collect_list;
    let realUrl = `${app.globalData.url}/editor/image/${list[index].name}`
    let id = list[index].sticker_id
    wx.getImageInfo({
      src: `${app.globalData.url}/editor/image/${list[index].name}`,
      success: res => {
        
        this.setData({
          graph: {
            id: id,
            w: 200,
            h: 200,
            type: 'sticker',
            url: res.path,
            realUrl: realUrl,
            sticker_name:list[index].name,
          }
        })
      }
    })
  },
  sticker_click: function (e) {
    const index = e.target.dataset.index;
    const list = this.data.sticker_list;
    let realUrl = `${app.globalData.url}/editor/image/${list[index].name}`
    let id = list[index].sticker_id
    wx.getImageInfo({
      src: `${app.globalData.url}/editor/image/${list[index].name}`,
      success: res => {
        this.setData({
          graph: {
            id: id,
            w: 200,
            h: 200,
            type: 'sticker',
            url: res.path,
            realUrl: realUrl,
            sticker_name:list[index].name,
          }
        })
      }
    })
  },
})